package interview.sort;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description: 插入排序
 * User: xxm
 * Date: 2018-04-02
 * Time: 23:45
 */
public class InsertionSort {

    public static int[] insertionSort(int[] array) {
        if (array.length == 0) {
            return array;
        }

        // 当前元素下标
        int currentValue;
        // 假设首元素有序，所以array.length - 1
        for (int i = 0; i < array.length - 1; i++) {
            currentValue = array[i + 1];
            int preIndex = i;
            // 当前的元素小于前一个，前插
            while (preIndex >= 0 && currentValue < array[preIndex]) {
                // 前面元素后移
                array[preIndex + 1] = array[preIndex];
                // 下标后移
                preIndex--;
            }
            array[preIndex + 1] = currentValue;
        }
        return array;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(
                InsertionSort.insertionSort(new int[]{0, -1, 2, -5, -20, -10})
        ));

        System.out.println(Arrays.toString(
                InsertionSort.insertionSort(new int[]{})
        ));

        System.out.println(Arrays.toString(
                InsertionSort.insertionSort(new int[]{4, 4, 4})
        ));

        System.out.println(Arrays.toString(
                InsertionSort.insertionSort(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9})
        ));

        System.out.println(Arrays.toString(
                InsertionSort.insertionSort(new int[]{9, 8, 7, 6, 5, 4, 3, 2, 1})
        ));

        System.out.println(Arrays.toString(
                InsertionSort.insertionSort(new int[]{31, 50, 12, 44, 2, 55, 78, 43, 24})
        ));
    }
}
